package com.hsu.hsurpc.serializer;

import java.io.*;

/**
 * @Author Hsu琛君珩
 * @Date 2024-09-17 20:49
 * @Description
 * @Version: v1.0.0
 */
public class JdkSerializer implements Serializer{

    /**
     * 序列化
     *
     * @param object 需要序列化的对象
     * @return 序列化后对象
     * @param <T> 序列化后的字节数组
     * @throws IOException 当序列化发生错误时抛出异常
     */
    @Override
    public <T> byte[] serialize(T object) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        return outputStream.toByteArray();
    }

    /**
     * 反序列化
     *
     * @param bytes 需要反序列化的字节数组
     * @param type 目标对象的类型
     * @return 反序列化后的对象
     * @param <T> 目标对象的类型
     * @throws IOException 当反序列化发生错误时抛出异常
     */
    @Override
    public <T> T deserialize(byte[] bytes, Class<T> type) throws IOException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        try {
            return (T) objectInputStream.readObject();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            objectInputStream.close();
        }
    }
}
